﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BIZ;
using DAL;

namespace SinhNhat.admin
{
    public partial class EditProduct : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lblHeader.Text = "Create product";
                PopulateRootCategories();

                //save state
                if (Request.Params["productID"] == null)
                {
                    chkInStock.Checked = true;
                }
                //edit state
                else
                {
                    Guid productID = WebUtils.ToGuid(Request.Params["productID"]);
                    if (!productID.Equals(Guid.Empty))
                    {
                        ProductBIZ productBIZ = new ProductBIZ();
                        PRODUCT product = productBIZ.GetByID(productID);

                        if (product == null)
                        {
                            Response.Write("<script type='text/javascript'>alert('Product ID is not correct');window.location = '/admin/AdminProduct.aspx';</script>");
                        }
                        else
                        {
                            txtName.Text = product.Name;
                            //txtUrl.Text = WebUtils.EditURL(product.Url);

                            if (WebUtils.FileExist(Server.MapPath(product.Image)))
                            {
                                imgProduct.ImageUrl = product.Image;
                            }
                            else
                            {
                                imgProduct.ImageUrl = "/data/images/no_image.jpg";
                            }
                            imgProduct.Visible = true;
                            txtDescription.Text = product.Description;
                            txtPrice.Text = product.Price.ToString();
                            lbCategory.SelectedValue = product.CategoryID.ToString();
                            chkInStock.Checked = product.InStock.Value;

                            hdServiceID.Value = productID.ToString();
                            hdUrlOld.Value = product.Url;

                            this.Page.Header.Title = "Edit | " + product.Name;
                            lblHeader.Text = "Edit product";
                        }
                    }
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            btnSave.Click += new EventHandler(btnSave_Click);
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            UrlBIZ.GetAllUrl();
            string url = WebUtils.CorrectURL(txtName.Text);

            ACCOUNT account = (ACCOUNT)Session["account"];
            if (account == null)
            {
                Response.Redirect("/Login.aspx");
            }

            ProductBIZ productBIZ = new ProductBIZ();
            PRODUCT product = new PRODUCT();
            product.Name = txtName.Text;
            product.Url = url;

            if (fuProduct.HasFile)
            {
                string ExtensionImage = WebUtils.FindExtension(fuProduct.FileName);
                if (WebUtils.checkImageFile(ExtensionImage))
                {
                    string fileName = "/data/images/" + Guid.NewGuid().ToString() + ExtensionImage;
                    fuProduct.SaveAs(Server.MapPath(fileName));
                    product.Image = fileName;
                    lblErrorImg.Visible = false;
                    
                    //delete old image
                    string imgPath = imgProduct.ImageUrl;
                    if (imgPath.Equals(string.Empty) == false && imgPath.Equals("/data/images/no_image.jpg") == false)
                    {
                        WebUtils.deleteFile(Server.MapPath(imgPath));
                    }
                }
                else
                {
                    lblErrorImg.Visible = true;
                    return;
                }
            }
            else
            {
                string imgPath = imgProduct.ImageUrl;
                if (imgPath.Equals(string.Empty) || imgPath.Equals("/data/images/no_image.jpg"))
                {
                    product.Image = string.Empty;
                }
                else
                {
                    product.Image = imgProduct.ImageUrl;
                }
            }

            product.CategoryID = WebUtils.ToGuid(lbCategory.SelectedValue);
            product.Description = txtDescription.Text;
            product.Price = decimal.Parse(txtPrice.Text);
            product.InStock = chkInStock.Checked;

            if (hdServiceID.Value.Equals(string.Empty))
            {
                //check url
                if (UrlBIZ.CheckPathExist(url) != PathType.PhysicalPath)
                {
                    lblError.Visible = true;
                    return;
                }

                product.AccountID = account.AccountID;
                product.IsLock = false;

                productBIZ.Insert(product);
            }
            else
            {
                //check url
                if (!hdUrlOld.Value.Equals(url))
                {
                    if (UrlBIZ.CheckPathExist(url) != PathType.PhysicalPath)
                    {
                        lblError.Visible = true;
                        return;
                    }
                }

                Guid productID = WebUtils.ToGuid(hdServiceID.Value);
                product.ProductID = productID;
                productBIZ.Edit(product);
            }

            Response.Redirect("/admin/AdminProduct.aspx");
        }

        private void PopulateRootCategories()
        {
            lbCategory.Items.Clear();
            CategoryBIZ categoryBIZ = new CategoryBIZ();
            lbCategory.DataSource = categoryBIZ.GetParentNode();
            lbCategory.DataTextField = "CategoryName";
            lbCategory.DataValueField = "CategoryID";
            lbCategory.DataBind();
            PopulateChildNode(lbCategory, categoryBIZ);
        }

        private void PopulateChildNode(ListBox root, CategoryBIZ categoryBIZ)
        {
            for (int i = 0; i < root.Items.Count; i++)
            {
                List<CATEGORY> listchild = categoryBIZ.GetChildNode(root.Items[i].Value);
                if (listchild.Count() <= 0) continue;
                string prefix = string.Empty;
                while (root.Items[i].Text.StartsWith("-"))
                {
                    prefix += root.Items[i].Text.Substring(0, 3);
                    root.Items[i].Text = root.Items[i].Text.Remove(0, 3);
                }
                root.Items[i].Text = prefix + root.Items[i].Text;
                foreach (CATEGORY child in listchild)
                {
                    ListItem list = new ListItem
                    {
                        Text = prefix + @"---" + child.CategoryName,
                        Value = child.CategoryID.ToString()
                    };
                    root.Items.Insert(root.Items.IndexOf(root.Items[i]) + 1, list);
                }
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
            _FileBrowser.BasePath = "/ckfinder/";
            _FileBrowser.SetupCKEditor(txtDescription);

        }
    }
}